<?php
namespace app\services;

use Fate;
use fate\http\Request;

class VerifyCodeService {

    public function sendVerifyCode($code) {
        $req = Request::getInstance();
        $ip = $req->getUserIP();
        $md5Code = md5(Fate::$app->securityKey . $ip . strtolower($code));

        // 5 min
        $age = 300;
        $lifeTime = time() + $age;
        //setcookie('f_vc', $md5Code, $lifeTime, '/');

        // setcookie 和输出图像的 header 冲突 故修改为此方法
        $gmt = gmdate('D, d M Y H:i:s T', $lifeTime);
        header("Set-Cookie: f_vc={$md5Code}; expires={$gmt}; Max-Age={$age}; path=/");
    }

    public function validateVerifyCode($code) {
        if(empty($code)) {
            return false;
        }

        $req = Request::getInstance();
        $ip = $req->getUserIP();
        $md5Code = isset($_COOKIE['f_vc']) ? $_COOKIE['f_vc'] : '';
        $userCode = md5(Fate::$app->securityKey . $ip . strtolower($code));

        if($userCode === $md5Code) {
            return true;
        }

        return false;
    }

}
